<template>
  <div class="user-list-container">
    <el-card shadow="hover">
      <template #header>
        <div class="table-header">
          <div class="left">
            <el-input
              v-model="searchQuery"
              placeholder="搜索用户名"
              style="width: 200px"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="right">
            <el-button 
              v-permission="'admin:manage'"
              type="primary" 
              @click="handleAdd"
            >
              新增用户
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="tableData" v-loading="loading" border stripe>
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="phone" label="手机号">
          <template #default="{ row }">
            {{ row.phone || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱">
          <template #default="{ row }">
            {{ row.email || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            <el-tag :type="getRoleTagType(row.role)">
              {{ getRoleName(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间">
          <template #default="{ row }">
            {{ new Date(row.created_at).toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-permission="'user:edit'"
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-permission="'admin:all'"
              size="small"
              type="warning" 
              @click="handleRole(row)"
            >
              角色
            </el-button>
            <el-button 
              v-permission="'admin:manage'"
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="role" v-if="hasPermission('admin:all')">
          <el-select v-model="form.role">
            <el-option
              v-for="(name, role) in roleOptions"
              :key="role"
              :label="name"
              :value="Number(role)"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../../store/user'
import request from '../../axios/request'

const userStore = useUserStore()
const { hasPermission } = userStore

// 数据列表相关
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const submitting = ref(false)
const formRef = ref(null)

const form = reactive({
  id: null,
  username: '',
  email: '',
  password: '',
  role: 3
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 角色选项
const roleOptions = {
  0: '超级管理员',
  1: '管理员',
  2: '主管',
  3: '员工',
  4: '老师'
}

// 获取角色名称
const getRoleName = (role) => roleOptions[role] || '未知角色'

// 获取角色标签类型
const getRoleTagType = (role) => {
  const types = {
    0: 'danger',
    1: 'warning',
    2: 'success',
    3: 'info',
    4: 'primary'
  }
  return types[role] || ''
}

// 修改加载用户列表的方法
const loadUsers = async () => {
  loading.value = true
  try {
    const params = {
      keyword: searchQuery.value,
      page: currentPage.value,
      pageSize: pageSize.value
    }
    const res = await request.get('/admin', { params })
    tableData.value = res.data
    total.value = res.total
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadUsers()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  loadUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUsers()
}

// 表单处理
const resetForm = () => {
  form.id = null
  form.username = ''
  form.email = ''
  form.password = ''
  form.role = 3
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const handleAdd = () => {
  dialogTitle.value = '新增用户'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  Object.assign(form, row)
  form.password = '' // 编辑时不显示密码
  dialogVisible.value = true
}

const handleRole = async (row) => {
  try {
    const { value } = await ElMessageBox.prompt('请选择新的角色', '修改角色', {
      inputType: 'select',
      inputValue: row.role,
      inputPlaceholder: '请选择角色',
      inputOptions: Object.entries(roleOptions).map(([value, label]) => ({
        value: Number(value),
        label
      }))
    })
    
    if (value !== null) {
      await request.patch(`/users/${row.id}/role`, { role: value })
      ElMessage.success('角色修改成功')
      loadUsers()
    }
  } catch (error) {
    console.error('修改角色失败:', error)
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      type: 'warning'
    })
    await request.delete(`/users/${row.id}`)
    ElMessage.success('删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    if (form.id) {
      await request.put(`/users/${form.id}`, form)
      ElMessage.success('更新成功')
    } else {
      await request.post('/users', form)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    loadUsers()
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 初始加载
loadUsers()
</script>

<style lang="scss" scoped>
.user-list-container {
  padding: 20px;
  
  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    .left {
      display: flex;
      gap: 16px;
      align-items: center;
    }
  }
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
    background-color: #fff;
  }
  :deep(.el-table) {
    // 表格样式优化
    th {
      background-color: #f5f7fa !important;
    }
    .el-table__row {
      transition: background-color 0.3s;
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
  :deep(.el-tag) {
    border-radius: 4px;
  }
  :deep(.el-pagination) {
    padding: 0;
    margin: 0;
    font-weight: normal;
    .el-pagination__total {
      margin-right: 16px;
    }
    .el-pagination__sizes {
      margin-right: 16px;
    }
  }
}
</style>